import React, { memo, useEffect, useState } from 'react'
import CommodityItem from '@/components/commodityItem/CommodityItem'
import {ResultList,HotSearch,SearchHeader} from './style.js'
import {reqSearchResult,reqSearch} from '@/api'
import { useHistory } from 'react-router-dom'

function Search() {
    const [searchKey,setSearchKey]=useState('')
    const [searchResult,setSearchResult]=useState([])
    const [hotSearchList,setHotSearchList]=useState([])
    const [isInput,setIsInput]=useState(false)
    const history = useHistory()

    const onSearch=()=>{
        if(!searchKey.trim()){
            history.goBack()
            return ;
        }
        reqSearchResult(searchKey)
            .then(res=>{
                setSearchResult(res.data.data.CommodityData)
                setSearchKey('')
                setIsInput(false)
            })
    }

    useEffect(()=>{
        reqSearch()
            .then(res=>{
                setHotSearchList(res.data.data.hotSearch)
            })
    },[])

    const searchInput=(e)=>{
        setSearchKey(e.target.value)
    }
    
    useEffect(()=>{
        if(searchKey){
            setIsInput(true)
        }
    },[searchKey])

    return (
        <div>
            <SearchHeader >
                <input type="text" placeholder='请输入内容' onChange={searchInput} value={searchKey} />
                <button onClick={onSearch}>{isInput?"搜索":"取消"}</button>
            </SearchHeader>
            {
                !searchResult.length
                ?<HotSearch>
                    <div className='hottitle'>热门搜索</div>
                    <div className='hotList'>
                        {
                            hotSearchList.map((item,index)=>{
                                return <div key={index+"hot"} onClick={()=>{setSearchKey(item)}} >{item}</div>
                            })
                        }
                    </div>
                </HotSearch>
                :<ResultList>
                    {
                        searchResult.map((item,index)=>{
                            return <CommodityItem CommodityData={item} key={index+"searchresult"} />
                        })
                    }
                </ResultList>
            }
        </div>
    )
}

export default memo(Search)
